package com.ygswglxt.leave.util;

import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 */
public class ExcelExportUtil {
    
    /**
     * 导出Excel文件
     * 
     * @param response HTTP响应
     * @param fileName 文件名（不含扩展名）
     * @param headers 表头数组
     * @param dataList 数据列表
     * @param fieldNames 数据字段名数组（与headers对应）
     */
    public static void exportExcel(HttpServletResponse response, String fileName, 
                                   String[] headers, List<Map<String, Object>> dataList, 
                                   String[] fieldNames) throws IOException {
        // 创建工作簿 - 使用反射创建XSSFWorkbook
        Workbook workbook = createWorkbook();
        Sheet sheet = workbook.createSheet("数据");
        
        // 创建样式
        CellStyle headerStyle = createHeaderStyle(workbook);
        CellStyle dataStyle = createDataStyle(workbook);
        
        // 创建表头
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }
        
        // 填充数据
        int rowNum = 1;
        for (Map<String, Object> data : dataList) {
            Row row = sheet.createRow(rowNum++);
            for (int i = 0; i < fieldNames.length; i++) {
                Cell cell = row.createCell(i);
                Object value = data.get(fieldNames[i]);
                if (value != null) {
                    if (value instanceof Number) {
                        cell.setCellValue(((Number) value).doubleValue());
                    } else {
                        cell.setCellValue(value.toString());
                    }
                } else {
                    cell.setCellValue("");
                }
                cell.setCellStyle(dataStyle);
            }
        }
        
        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
            // 设置最小列宽
            int columnWidth = sheet.getColumnWidth(i);
            if (columnWidth < 256 * 10) {
                sheet.setColumnWidth(i, 256 * 10);
            }
        }
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName + ".xlsx");
        
        // 写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    
    /**
     * 创建工作簿 - 使用反射创建XSSFWorkbook以避免编译时依赖问题
     */
    private static Workbook createWorkbook() throws IOException {
        try {
            // 尝试使用反射创建XSSFWorkbook
            Class<?> xssfWorkbookClass = Class.forName("org.apache.poi.xssf.usermodel.XSSFWorkbook");
            return (Workbook) xssfWorkbookClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new IOException("无法创建Excel工作簿，请确保poi-ooxml依赖已正确添加并刷新Maven项目。错误: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建表头样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }
    
    /**
     * 创建数据样式
     */
    private static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }
}

